package com.livepass.android.girlspicks.activities;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;

import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.livepass.android.girlspicks.MyApplication;
import com.livepass.android.girlspicks.R;
import com.livepass.android.girlspicks.adapters.NotificationAdapter;
import com.livepass.android.girlspicks.models.Article;
import com.livepass.android.girlspicks.models.Notification;
import com.livepass.android.girlspicks.utils.JSONParser;
import com.livepass.android.girlspicks.utils.Utilities;
import com.livepasspush.sdk.LivepassPushSDK;
import com.livepasspush.sdk.LivepassPushSDKConfig;
import com.livepasspush.sdk.LivepassPushSDKDelegate;
import com.livepasspush.sdk.util.LivepassPushSDKLog;

public class NotificationsActivity extends Activity implements LivepassPushSDKDelegate {

	private PullToRefreshListView lvNoti;
	private LinearLayout llLoading;
	NotificationAdapter notificationAdapter;
	private AsyncGetNotifList loader;
	private AsyncGetArticleDetail loaderArticleDetail;
	private AsyncSetReadNotif loaderRead;

	//private int notifCount;
	ArrayList<Notification> lisNotifications;
	public static ArrayList<String> listNotifRead;
	private int currentPage = 1;
	private boolean isLoadMore = true;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_notifications);

		llLoading = (LinearLayout) findViewById(R.id.llLoading);
		lisNotifications = new ArrayList<Notification>();
		listNotifRead = new ArrayList<String>();
		lvNoti = (PullToRefreshListView) findViewById(R.id.list_noti);
		
		//get list notifications
		loader = new AsyncGetNotifList();
		loader.execute("1");
		
		notificationAdapter = new NotificationAdapter(getApplicationContext(),
				R.layout.noti_list_item, lisNotifications);
		lvNoti.setAdapter(notificationAdapter);
		lvNoti.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				listNotifRead.add(lisNotifications.get(position-1).getNotifId());
				loaderArticleDetail = new AsyncGetArticleDetail();
				loaderArticleDetail.execute(lisNotifications.get(position-1).getArticleId());
				//set read notification
				loaderRead = new AsyncSetReadNotif();
				loaderRead.execute(lisNotifications.get(position-1).getNotifId());
			}
		});
		
		// Add an end-of-list listener
		lvNoti.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {

					@Override
					public void onLastItemVisible() {
						if (isLoadMore) {
							loader = new AsyncGetNotifList();
							++currentPage;
							loader.execute("" + currentPage);
							Log.d("PAGE", "" + currentPage);
						}
					}
				});
		
		
		// ファイル名を設定
        LivepassPushSDK.setConfigFilename(getApplicationContext(), LivepassPushSDKConfig.DEFAULT_PROPATY_FILE_NAME);
        // 設定値を読み込み（ファイルの）
        LivepassPushSDK livepasspushsdk = LivepassPushSDK.getInstatnce(this);
        // 新規の値を設定
        LivepassPushSDK.setPHDelegate(this);
        // UUIDを指定する場合は一時的にデフォルトの生成方法で生成されてしまうため、 必ず、start()以前に行うこと
        // setごとに更新される為、呼ばれるたびに値が変わるような取得方法を使用しないこと
        // setされていなければ、使用される際自動生成され保存される。
        // ValuePushSDK.setUUID(/* 生成したUUID文字列 */);
        LivepassPushSDK.setNotificationEnabled(true);
        LivepassPushSDK.setLocationEnabled(true);
        LivepassPushSDK.setLogTag("LivepassPushSDKSampleApp");
        livepasspushsdk.start();
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		if(notificationAdapter!=null) notificationAdapter.notifyDataSetChanged();
	}

	public void doBack(View v) {
		setResult(RESULT_CANCELED);
		finish();
	}

	private class AsyncGetNotifList extends
			AsyncTask<String, JSONObject, ArrayList<Notification>> {

		@Override
		protected ArrayList<Notification> doInBackground(String... params) {

			Map<String, String> param = new LinkedHashMap<String, String>();
			param.put("id", "girlspicks");
			param.put("secret", "UCzCRQAAAIBVDBPwLuaV8o9mu");
			param.put("client_id", MyApplication.USER_ID);
			param.put("page", params[0]);

			JSONObject jsonObject = null;
			ArrayList<Notification> listNotifications = null;
			try {
				jsonObject = Utilities.doPostRequest(
						"http://girlspicks.co/api/get_notif_list", param);
				// Parse the JSON Object
				JSONParser parser = new JSONParser();
				listNotifications = parser.parserNotification(jsonObject);
			} catch (ClientProtocolException e1) {
				e1.printStackTrace();
			} catch (IOException e1) {
				e1.printStackTrace();
			} catch (JSONException e) {
				e.printStackTrace();
			}
			return listNotifications;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			llLoading.setVisibility(View.VISIBLE);
		}

		/* (non-Javadoc)
		 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
		 */
		@Override
		protected void onPostExecute(ArrayList<Notification> result) {

			if (result != null && result.size() != 0) {
				Notification notification;
				for (int i = 0; i < result.size(); i++) {
					notification = new Notification();
					notification.setNotifId(result.get(i).getNotifId());
					notification.setFromClient(result.get(i).getFromClient());
					notification.setToClient(result.get(i).getToClient());
					notification.setArticleId(result.get(i).getArticleId());
					notification.setType(result.get(i).getType());
					notification.setIsRead(result.get(i).getIsRead());
					notification.setCreatedAt(result.get(i).getCreatedAt());
					//notification.setUpdatedAt(result.get(i).getUpdatedAt());
					lisNotifications.add(notification);
				}
				//set load more
				if(result.size()<10) {
					isLoadMore = false;
				}
				//lisNotifications = result;
				notificationAdapter.notifyDataSetChanged();
			}
			llLoading.setVisibility(View.GONE);
		}

	}
	
	private class AsyncGetArticleDetail extends
			AsyncTask<String, JSONObject, Article> {

		@Override
		protected Article doInBackground(String... params) {

			Map<String, String> param = new LinkedHashMap<String, String>();
			param.put("id", "girlspicks");
			param.put("secret", "UCzCRQAAAIBVDBPwLuaV8o9mu");
			param.put("article_id", params[0]);

			JSONObject jsonObject = null;
			Article article = null;
			try {
				jsonObject = Utilities.doPostRequest(
						"http://girlspicks.co/api/get_article_by_id", param);
				if("0".equals(jsonObject.getString("status"))) {
					// Parse the JSON Object
					JSONParser parser = new JSONParser();
					article = parser.parserArticleDetail(jsonObject);
				} else {
					article = null;
				}
			} catch (ClientProtocolException e1) {
				e1.printStackTrace();
			} catch (IOException e1) {
				e1.printStackTrace();
			} catch (JSONException e) {
				e.printStackTrace();
			}
			return article;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected void onPostExecute(Article result) {

			if (result != null) {
				Intent intent = new Intent(NotificationsActivity.this, ArticleActivity.class);
				Bundle bun = new Bundle();
				bun.putSerializable("article", result);
				intent.putExtras(bun);
				startActivity(intent);
			} else {
				AlertDialog.Builder builder = new AlertDialog.Builder(NotificationsActivity.this);
				// Add the buttons
				builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
					}
				});
				builder.setTitle("Data not found");
				// Create the AlertDialog
				builder.create().show();
				notificationAdapter.notifyDataSetChanged();
			}
		}
	}
	
	private class AsyncSetReadNotif extends
			AsyncTask<String, Void, String> {

		@Override
		protected String doInBackground(String... params) {

			String res = null;
			Map<String, String> param = new LinkedHashMap<String, String>();
			param.put("id", "girlspicks");
			param.put("secret", "UCzCRQAAAIBVDBPwLuaV8o9mu");
			param.put("notif_id", params[0]);
			param.put("client_id", MyApplication.USER_ID);

			JSONObject jsonObject = null;
			try {
				jsonObject = Utilities.doPostRequest(
						"http://girlspicks.co/api/set_read_notif", param);
				// Parse the JSON Object
				JSONParser parser = new JSONParser();
				res = parser.parserSetReadNotification(jsonObject);
			} catch (ClientProtocolException e1) {
				e1.printStackTrace();
			} catch (IOException e1) {
				e1.printStackTrace();
			} catch (JSONException e) {
				e.printStackTrace();
			}
			return res;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected void onPostExecute(String result) {

			if (result != null) {
				//TODO
			}
		}
	}
	
	@Override
    public void didRegisterGCM(String registerId) {
        LivepassPushSDKLog.d("REGISTER_GCM", "Success registerID = " + registerId);
    }

    @Override
    public void didFailToRegisterGCMWithError() {
        LivepassPushSDKLog.d("REGISTER_GCM", "Failed");

    }

    @Override
    public void didRegisterRegIDWithUserInfo() {
        LivepassPushSDKLog.d("REGISTER_PUSH_SERVER", "Success");
    }

    @Override
    public void didFailToRegisterRegIDWithError() {
        LivepassPushSDKLog.d("REGISTER_PUSH_SERVER", "Failed");
    }

    @Override
    public void didCommitData() {
        LivepassPushSDKLog.d("COMMIT_DATA", "Success");
    }

    @Override
    public void didFailToCommitDataWithError() {
        LivepassPushSDKLog.d("COMMIT_DATA", "Failed");
    }

    @Override
    public boolean didReceivePushMessage(String json) {
        return true;
    }

    @Override
    public void didReceiveRemotePushNotificationWithStateActive(String json) {
        LivepassPushSDKLog.d("DID_RECEIVE_REMOTE_PUSHNOTIFICAION", json);
        ContentFragment.addList(json);
    }

    @Override
    public void didReceiveRemotePushNotificationWithStateInactive(String json) {
        LivepassPushSDKLog.d("DID_RECEIVE_REMOTE_PUSHNOTIFICAION", json);
        ContentFragment.addList(json);
    }

    @Override
    public void livepasspushsdkViewWillAppear() {
        LivepassPushSDKLog.d("VIEW_WILL_APPEAR", "Success");
    }

    @Override
    public void livepasspushsdkViewDidAppear() {
        LivepassPushSDKLog.d("VIEW_DID_APPEAR", "Success");
    }

    @Override
    public void livepasspushsdkViewWillDisappear() {
        LivepassPushSDKLog.d("VIEW_WILL_DISAPPEAR", "Success");
    }

    @Override
    public void livepasspushsdkViewDidDisappear() {
        LivepassPushSDKLog.d("VIEW_DID_DISAPPEAR", "Success");
    }
}
